package com.zxw.mallafter.api;

import model.Category;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import service.CategoryService;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "/api/v1/category",produces = "application/json;charset=UTF-8")
public class CategoryApi {
    @DubboReference
    private CategoryService categoryService;
    //查询所有
    @GetMapping
    public Map<String,Object> getall(){
        List<Category> categories = categoryService.findAll();
        return Map.of("success", true, "data", categories);
    }
    //查询一棵树
    @GetMapping("/tree")
    public Map<String,Object> findtree(){
        Category category = categoryService.findtree();
        return Map.of("success", true, "data", category);
    }
    @GetMapping("tiaojian")
    public Map<String,Object> findtree(Category category){
        System.out.println(category.getDescription());
        Category c = categoryService.tiaojian(category);
        if(c==null){
            return Map.of("success", false, "error", "查询的类别不存在");
        }
        return Map.of("success", true, "data", c);
    }
    @GetMapping("/name")
    public Map<String, Object> findname(@RequestParam Integer id) {

        String name = this.categoryService.findname(id);

        return Map.of("name", name, "success", true);
    }




    @GetMapping("/id/{id}")
    public Map<String, Object> findById(@PathVariable Integer id) {
        Category category = this.categoryService.findById(id);
        if (category == null) {
            return Map.of("success", false, "error", "查询的类别不存在");
        }
        return Map.of("data", category, "success", true);
    }

    @PostMapping
    public Map<String, Object> save(@RequestBody Category category) {
        if (!StringUtils.hasText(category.getName())) {
            return Map.of("success", false, "error", "类别名称不可为空");
        }
        if(!StringUtils.hasText(category.getDescription())){
            return Map.of("success", false, "error", "类别描述不可为空");
        }

       boolean success = this.categoryService.save(category);
      return Map.of("success", success);
    }

    @PutMapping
    public Map<String, Object> update(@RequestBody Category category) {
        boolean success = this.categoryService.update(category);
        return Map.of("success", success);
    }

    @GetMapping("/delete")
    public Map<String, Object> deleteByIds(@RequestParam Integer id) {

            int rows = this.categoryService.deleteById(id);

        return Map.of( "success", rows > 0);
    }




}
